import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import services from '@/services/demo';
import { Button, Divider, Drawer, Input, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import ModalCard from '@/components/ModalCard';
import { remove } from '@/services/demo/AddressController';

const { queryList, add, modify, removeById } =
  services.AddressController;

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.AddressType) => {
  const hide = message.loading('正在添加');
  try {
    await add({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: Partial<API.AddressType>) => {
  const hide = message.loading('正在修改');
  try {
    await modify(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};


const handleRemove = async (id: string) => {
  const hide = message.loading('正在删除');
  try {
    await removeById(id);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handleRemoveSelected = async (selectedRows: API.AddressType[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await remove({
      ids: selectedRows.map(it => it.id) || []
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


function AddressPage() {
	const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<API.AddressType | {}>({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.AddressType>();
  const [selectedRowsState, setSelectedRows] = useState<API.AddressType[]>([]);
  const columns: ProDescriptionsItemProps<API.AddressType>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
			hideInSearch: true,
      renderFormItem: () => <Input disabled/>
    },
    {
      title: '地址',
      dataIndex: 'name',
      valueType: 'text',
    },
		{
      title: '经度',
      dataIndex: 'longitude',
			valueType: 'text',
			hideInSearch: true,
    },
    {
      title: '维度',
      dataIndex: 'latitude',
			valueType: 'text',
			hideInSearch: true,
    },
		{
      title: '范围',
      dataIndex: 'aRange',
			valueType: 'text',
			hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Button type='primary'
            onClick={() => {
              setStepFormValues((_: any) => ({...record}));
              handleUpdateModalVisible(true);
            }}
          >
            修改
          </Button>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除吗？"
						onConfirm={async () => {
              const success = await handleRemove(record.id)
              if (success) {
                actionRef.current?.reloadAndRest?.()
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button type='primary' danger >删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '地址管理',
      }}
    >
      <ProTable<API.AddressType>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => handleModalVisible(true)}
          >
            新建
          </Button>,
        ]}
        request={queryList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={async () => {
              await handleRemoveSelected(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>批量删除</Button>
          </Popconfirm>
        </FooterToolbar>
      )}
      <ModalCard
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable<API.AddressType, API.AddressType>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
        />
      </ModalCard>
      { stepFormValues && Object.keys(stepFormValues).length > 0 ?
        <ModalCard
          onCancel={() => {
            handleUpdateModalVisible(false)
            setStepFormValues({})
          }}
          modalVisible={updateModalVisible}
        >
          <ProTable<API.AddressType, API.AddressType>
            form={{initialValues: stepFormValues}}
            onSubmit={async (value) => {
              const success = await handleUpdate(value);
              if (success) {
                handleUpdateModalVisible(false);
                setStepFormValues({})
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="id"
            type="form"
            columns={columns}
          />
        </ModalCard>
        :null        
      }

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.id && (
          <ProDescriptions<API.AddressType>
            column={2}
            title={row?.id}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.id,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
}

export default AddressPage;